package utils;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

public class EncryptAndSignService {

	Logger logger = LoggerFactory.getLogger(getClass());
	
	/**
	 * 商户号，根据商户号获取证书文件
	 */
	private String secuNo;
	
	private String errorMsg;
	
	/**
	 * 明文
	 */
	private String plainTxt;
	
	private String cipherTxt;
	
	public EncryptAndSignService(String secuNo, String plainTxt){
		this.secuNo = secuNo;
		this.plainTxt = plainTxt;
	}
	
	public EncryptAndSignService(String secuNo, Object obj){
		this.secuNo = secuNo;
		this.plainTxt = JSON.toJSONString(obj);
	}
	
	public boolean encryptAndSign(String secuNo){
		String sign = "";
		
		try {
			sign = SM2Utils.signRaw(plainTxt, secuNo);
		} catch (Exception e) {
			logger.error("签名失败。", e);
			errorMsg = "签名失败";
			return false;
		}
		
		Map<String, String> paramMap = new HashMap<String, String>();
		paramMap.put(Constants.PARAM_SIGN, sign);
		paramMap.put(Constants.PARAM_BODY, plainTxt);
		
		String plainTxt = JSON.toJSONString(paramMap);	//待加密字符串
		try {
			logger.info("明文：" + plainTxt);
			cipherTxt = SM2Utils.encrypt(plainTxt);
			logger.info("密文：" + cipherTxt);
		} catch (Exception e) {
			logger.error("加密失败。", e);
			errorMsg = "加密失败";
			return false;
		}
		return true;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public String getCipherTxt() {
		return cipherTxt;
	}

	public void setCipherTxt(String cipherTxt) {
		this.cipherTxt = cipherTxt;
	}
}
